package org.geektimes.configuration.microprofile.config.source;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class OsPropertiesConfigSource extends MapPropertiesSource {

    private final String WINDOWS = "windows";

    public OsPropertiesConfigSource() {
        super("OS System Properties", 500);
    }

    public Map<String, String> getOsEnv() throws IOException {

        Map<String, String> prop = new HashMap<>();
        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains(WINDOWS)) {
            Process p = Runtime.getRuntime().exec("cmd /c set");
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                int i = line.indexOf("=");
                if (i > -1) {
                    String key = line.substring(0, i);
                    String value = line.substring(i + 1);
                    prop.put(key, value);
                }
            }
            return prop;
        } else {
            return System.getenv();
        }

    }


    @Override
    public void readProperties(Map properties) throws Throwable{
        properties.putAll(getOsEnv());
    }

}
